# -*- coding: utf-8 -*-
import os
from math import cos, sin, radians
from table import Table

'''
Проверка расширения файла
Возращает True, если файл заканчивается
на @extension
'''
def checkFileExtension(extension):
    extLen = len(extension);
    return lambda x: (x[-extLen:] == extension and len(x) > extLen)

'''
Возвращает dict(), ключами которых являются имена файлов
значениями являются экземпляры dict(),
содержащие значения таблицы
'''
def loadTablesFromDir(directory):
    fileList = filter(checkFileExtension('.csv') , os.listdir(directory))
    tables = dict()
    for fileName in fileList:
        tables[fileName[:-4]] = Table(directory + os.sep + fileName)
    return tables

'''
Возвращает проекции вектора направления
ветра по углу и скорости
'''
def getWxWz(aw, V):
    aw = radians(aw * 6)
    Wx = -V * cos(aw)
    Wz = V * sin(aw)
    Wx = round(Wx)
    Wz = round(Wz)
    return (Wx, Wz)

'''
Возвращает данные из метео-бюллетеня @bulletin
'''
def bulletParse(bulletin):
    mdata = bulletin.split('-')
    h_ams = int(mdata[2])
    dh_ams = int(mdata[3][:3])
    if dh_ams > 500:
        dh_ams = 500 - dh_ams   
    dT_ams = int(mdata[3][3:])
    if dT_ams > 50:
        dT_ams = 50 - dT_ams
    
    Ys = map(int, mdata[4::2])
    mdata = mdata[5::2]
    
    groups = []
    
    for x in mdata:
        dT = int(x[:2])
        if dT > 50:
            dT = 50 - dT
        aw = int(x[2:4])
        V = int(x[4:])
        groups.append((dT, aw, V))
    
    groups = dict(zip(Ys, groups))
    
    return (h_ams, dh_ams, dT_ams, groups)

def getGroup(y, groups):
    y /= 100
        
    if y in groups:
        return groups[y]
    else:
        less = filter(lambda x: x < y, groups)
        more = filter(lambda x: x > y, groups)
        
        if len(more) == 0:
            return groups[max(less)]
        else:
            return groups[min(more)]        

def computeAll(tables, bull, Tz, h_op, Z, alpha, dV0, dist):
    (h_ams, dh_ams, dT_ams, groups) = bulletParse(bull)
    del(dT_ams)
    dTz = Tz - 15
    dh_op = dh_ams + (h_ams - h_op) / 10.0
    table = tables[Z]
    
    distants = []
    directions = []
    
    for x in dist:
        row = table.searchDistance(x)
                
        (Dt, aw, V) = getGroup(row.Ys, groups)
        
        Wx, Wz = getWxWz(alpha - aw, V)
        
        dh_op = round(dh_op)
        Dt = round(Dt)
        dTz = round(dTz)
        
        Dsum = 0.1 * (row.dXw * Wx + row.dXh * dh_op + row.dXt * Dt + row.dXtz * dTz) + row.dXV0 * dV0
        dov = row.Z + 0.1 * row.dZw * Wz
        
        Dsum = round(Dsum)
        dov = round(dov)
        
        distants.append(Dsum)
        directions.append(dov)
        
    return distants, directions

if __name__ == '__main__':
    tables = loadTablesFromDir('../../tables')
    
    